/*
*	模态框插件
*/

;(function (jQuery) {
	'use strict';

	var Modal = function (options, deferred) {
		var self = this;
		self.element = $($.modal.template.whole);
		self.options = options;
		self.deferred = deferred;

		if (! $(document.body).find('.modal')[0]) {
			$(document.body).append(
				self.element.css('margin-top', ($(window).scrollTop() + 100))
			);
			if (self.options.fullscreen) {
				self.options.drag = false;
				self.element.css({
					'bottom': 0 - $(window).scrollTop(),
					'border-radius': 0,
				});
			}
		}			

		//  添加主题
		if (self.options.theme) {
			self.element.addClass(self.options.theme);
		}
		//  添加头部
		if (self.options.tittle) {
			self.element.append(
				$($.modal.template.head).html(self.options.tittle)
			);
		}
		//  添加主体
		if (self.options.content) {
			self.element.append(
				$($.modal.template.main).html(self.options.content)
			);
		}
		//  添加底部
		if (self.options.okay || self.options.cancel) {
			self.element.append($($.modal.template.foot));
			//  确认
			if (self.options.okay) {
				$('.modal-foot').append(
					$($.modal.template.okay_btn)
						.html(self.options.okay)
						.attr('data-okay', 'modal')
				);
				self.element.on('click.modal.okay', '[data-okay="modal"]', function (e) {
					e.preventDefault();
					//  如果存在输入框，获取其值
					if (self.options.input) {
						var prompt_content = $('input[name="prompt_content"]').val();
						window.prompt_content = prompt_content;
					}
					self.hide(true);
				});				
			}
			if (self.options.cancel) {
				$('.modal-foot').append(
					$($.modal.template.cancel_btn)
						.html(self.options.cancel)
						.attr('data-cancel', 'modal')
				);
				self.element.on('click.modal.cancel', '[data-cancel="modal"]', function (e) {
					e.preventDefault();
					self.hide(false);
				});				
			}
		}
		//  关闭按钮
		if (self.options.close) {
			self.element.append(
				$($.modal.template.close_btn)
					.html(self.options.close)
					.attr('data-close', 'modal')
			);
			self.element.on('click.modal.close', '[data-close="modal"]', function (e) {
				e.preventDefault();
				self.hide(false);
			});				
		}
		//  动画效果
		if (self.options.transition) {
			self.element.addClass(self.options.transition);
		}

		//  initialization
		self.display = false;
		self.show();

		//  允许拖拽
		if (self.options.drag) {
			self.drag(
				self.element.css('margin-top'), 
				($(window).width() - self.element.width()) / 2
			);
		}
		return self;
	};

	Modal.prototype = {
		constructor: Modal,
		//  设置居中
		set_center: function () {
			var self = this,
				w_w = $(window).width(),
				w_h = $(window).height(),
				s_w = self.element.width(),
				s_h = self.element.height(),
				w_sc = $(window).scrollTop();
			self.element
				.addClass('center')
				.css({
					'margin': 0,
					'left': (w_w - s_w) / 2, 
					'top': (w_h - s_h) / 2 + w_sc,
				});
			return self;
		},
		
		//  显示
		show: function () {
			var self = this, 
				e = $.Event('show.modal');
			if (self.display) {
				return;
			}
			//  居中显示
			if (self.options.center) {
				self.set_center();
			}
      		// 	全屏显示
      		if (self.options.fullscreen) {
      			self.element
      				.addClass('full')
      				.css('top', $(window).scrollTop());
      		}
      		self.element.trigger(e).css('display', 'block');
			if (self.options.transition) {
		    	//  force reflow
        		self.element[0].offsetWidth;
        		self.element.addClass('in');
      		}
      		$(document.body).addClass('lock');
      		//  移动端锁屏
      		$(document.body).on('touchmove.lock', function (e) {
      			e.preventDefault();
      		});
      		//  遮罩
      		if (self.options.backdrop) {
      			$(document.body).append(
      				$($.modal.template.backdrop)
      					.attr('data-backdrop', 'modal')
      					.css('height', $(document).height())
      			);   			
      			if (typeof self.options.backdrop === 'string') {
      				$(document.body).on('click.modal.backdrop', '[data-backdrop="modal"]', function (e) {
      					e.preventDefault();
      					self.hide(false);
      				});
      			}
      		}
			self.display = true;
			return self;
		},

		//  隐藏
		hide: function (result) {
			var self = this, 
				e =  $.Event('hide.modal');
			if (!self.display) {
				return;
			}
			if (self.options.transition) {
				//  动画结束
				self.element.one('transitionend, webkitTransitionEnd', function () {
		            self.element.removeClass('out').css('display', 'none');
		            $('.modal-backdrop').remove();
					$(document.body).removeClass('lock');
					$(document.body).off('.lock');
		            self.display = false;
		            self.destroy();
	        	});
				self.element.trigger(e).removeClass('in').addClass('out');
				// force reflow
				self.element[0].offsetWidth; 
      		}
      		else {
      			self.element.trigger(e).css('display', 'none');
      			$('.modal-backdrop').remove();
				$(document.body).removeClass('lock');
				$(document.body).off('.lock');
				self.display = false;
				self.destroy();
      		}
			if (self.deferred && result !== undefined) {
	        	if (result) {
	        		self.deferred.resolve(result);
	        	}
	        	else {
	        		self.deferred.reject(result);
	        	}
	        }
			return self;
		},

		//  移除
		destroy: function () {
			var self = this;
			if (!self.display) {
				self.element.off('.modal').remove();
				self = null;
				return false;
			}
			else {
				self.hide();
			}
		},

		//  拖拽
		drag: function (p_t, p_l) {
			var self = this,
				w_w = $(window).width(),
				w_h = $(window).height(),
				w_sc = $(window).scrollTop(),
				s_w = self.element.width(),
				s_h = self.element.height(),
				$document = $(document),
				$target = self.element.find('.modal-head');

			//  改变定位方式
			if (! self.options.center) {
				self.element.css({
					'top': p_t,
					'left': p_l,
					'margin': 0,
				});
			}
			//  bind
			$target.on('mousedown.modal', drag_start);

			//  拖拽 —— 鼠标按下
			function drag_start(e) {
				var land_x = e.clientX - self.element.offset().left,
					land_y = e.clientY - self.element.offset().top;
				drag_move(land_x, land_y);
				drag_end();
				return false;
			}

			//  拖拽 —— 鼠标移动
			function drag_move(land_x, land_y) {
				$document.on('mousemove.modal', function (e) {
					e.preventDefault();
					var l = e.clientX - land_x, 
						t = e.clientY - land_y;
					//  fix area
					if (l < 0) {
						l = 0;
					}
					else if (l > w_w - s_w) {
						l = w_w - s_w;
					}
					if (t < 0 + w_sc) {
						t = 0 + w_sc;
					}
					else if (t > w_h - s_h + w_sc) {
						t = w_h - s_h + w_sc;
					}
					self.element.css({
						'left': l, 
						'top': t,
					});
				});
			}

			//  拖拽 —— 鼠标按键抬起
			function drag_end() {
				$document.on('mouseup.modal', function (e) {
					e.preventDefault();
					$document.off('.modal');
				});
			}
			return self;
		}
	};

	//  modal(confirm)
	$.modal = function (options) {
		if (typeof options === 'string') {
			options = {
				content: options,
			};
		}
		options = $.extend({}, $.modal.defaults, options);
		var deferred = $.Deferred(),
			modal = new Modal(options, deferred);
		return deferred;
	};

	//  alert
	$.alert = function (options) {
		if (typeof options === 'string') {
			options = {
				content: options,
			};
		}
		options = $.extend({}, $.modal.defaults, options, {
			cancel: '',
		});
		$.modal.template.okay_btn = 
			'<a href="javascript:;" class="modal-okay"></a>';
		var deferred = $.Deferred(),
			modal = new Modal(options, deferred);
		return deferred;
	}

	//  prompt
	$.prompt = function (options) {
		if (typeof options === 'string') {
			options = {
				content: options,
			};
		}
		options = $.extend({}, $.modal.defaults, options, {
			content: '<input type="text" name="prompt_content" value="" placeholder="' + $.modal.defaults.placeholder + '"/>',
			input: true,
		});
		var deferred = $.Deferred(),
			modal = new Modal(options, deferred);
		return deferred;
	}

	//  模板
	$.modal.template = {
		whole: '<div class="modal"></div>',
		head: '<div class="modal-head"></div>',
		main: '<div class="modal-main"></div>',
		foot: '<div class="modal-foot"></div>',
		okay_btn: '<a href="javascript:;" class="modal-okay"></a>',
		close_btn: '<a href="javascript:;" class="modal-close"></a>',
		cancel_btn: '<a href="javascript:;" class="modal-cancel"></a>',
		backdrop: '<div class="modal-backdrop"></div>',
	};

	//  默认参数
	$.modal.defaults = {
		theme: 'theme_a',
		tittle: 'tittle',
		close: '&times;',
		content: 'this is a modal',
		placeholder: 'please input',
		okay: 'okay',
		cancel: 'cancel',
		backdrop: 'true',
		transition: 'scale',
		fullscreen: false,
		input: false,
		center: false,
		drag: true,
	};
	
}($));
